package com.polaris.live.ui.message.utils

import android.view.View
import android.widget.TextView
import com.polaris.live.common.ext.convertArabicDigitsToNormal
import com.polaris.live.im.db.entity.MessageEntity
import com.polaris.live.im.sfs.TYPE_MESSAGE_GIFT
import com.polaris.live.im.utils.SessionUtils
import com.polaris.live.utils.BitwiseUtils
import java.util.concurrent.TimeUnit

/**
 * MessageAdapterUtils
 *
 * @author Created by lucas on 2023/10/21 14:15
 */
object MessageAdapterUtils {

    private val MIN_RECENT_TIME = TimeUnit.MINUTES.toMillis(5)

    /**
     * 显示消息时间
     */
    fun fillTimeStamp(list: List<MessageEntity>, text: TextView, position: Int, time: Long) {
        val message = getTimeItem(list, position + 1)
        val nowMsg = getTimeItem(list, position)
        if (nowMsg != null &&
            (BitwiseUtils.isBitwise(nowMsg.type, TYPE_MESSAGE_GIFT))
        ) {
            text.visibility = View.GONE
            return
        }

        if (time != 0L && message != null && time - message.timestamp < MIN_RECENT_TIME) {
            text.visibility = View.GONE
        } else {
            text.visibility = View.VISIBLE
            text.text = SessionUtils.periodMessageTime(time)?.convertArabicDigitsToNormal()
        }
    }

    private fun getTimeItem(list: List<MessageEntity>, position: Int): MessageEntity? {
        return if (position < 0 || position >= list.size) {
            null
        } else {
            list[position]
        }
    }
}